package com.reggie.Interceptor;

import com.reggie.constant.JwtClaimsConstant;
import com.reggie.context.BaseContext;
import com.reggie.properties.JwtProperties;
import com.reggie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理端JWT拦截器
 * */
@Component
@Slf4j
public class AdminJwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 创建拦截器统一进行JWT令牌校验
     * */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求：{}",request.getRequestURI());
        //判断是否是controller的方法
        if (! (handler instanceof HandlerMethod)){
            //直接放行，比如HTML页面等
            return true;
        }
        //从请求头获取JWT令牌
        String token=request.getHeader(jwtProperties.getAdminTokenName());
        try {
            //解析JWT令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //解析完令牌之后，获取当前员工的ID
            Long empid = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            //把获取到的员工ID存储进线程本地变量中
            BaseContext.setCurrentId(empid);
            return true;
        }catch (Exception e){
            log.info("令牌解析失败");
            response.setStatus(401);
            return false;
        }
    }
}
